package com.foreverwin.mes.production.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mes.common.enums.IDUtils;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.production.constant.Constants;
import com.foreverwin.mes.production.dto.CleanExeDto;
import com.foreverwin.mes.production.dto.CleanExeReviewDto;
import com.foreverwin.mes.production.model.CleanData;
import com.foreverwin.mes.production.model.CleanDataItem;
import com.foreverwin.mes.production.model.CleanExe;
import com.foreverwin.mes.production.mapper.CleanExeMapper;
import com.foreverwin.mes.production.model.CleanExeItem;
import com.foreverwin.mes.production.service.CleanDataItemService;
import com.foreverwin.mes.production.service.CleanDataService;
import com.foreverwin.mes.production.service.CleanExeItemService;
import com.foreverwin.mes.production.service.CleanExeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.production.vo.CleanExeReviewVo;
import com.foreverwin.mes.production.vo.CleanExeVo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * <p>
 * 清洁执行表 服务实现类
 * </p>
 *
 * @author Max
 * @since 2020-02-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CleanExeServiceImpl extends ServiceImpl<CleanExeMapper, CleanExe> implements CleanExeService {

    @Autowired
    public CleanExeMapper cleanExeMapper;
    @Autowired
    public CleanExeService cleanExeService;
    @Autowired
    public CleanDataService cleanDataService;
    @Autowired
    public CleanDataItemService cleanDataItemService;
    @Autowired
    public CleanExeItemService cleanExeItemService;

    @Override
    public Page<CleanExe> selectPage(FrontPage<CleanExe> frontPage, CleanExe cleanExe) {
        EntityWrapper<CleanExe> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(cleanExe);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<CleanExe> selectList(CleanExe cleanExe) {
        EntityWrapper<CleanExe> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(cleanExe);
        return super.selectList(queryWrapper);
    }

    /**
     * 查询任务明细及状态
     *
     * @param zCleanExeBo
     * @return
     */
    @Override
    public List<CleanExeVo> selectCleanTaskList(String zCleanExeBo) {
        return cleanExeMapper.selectCleanTaskList( zCleanExeBo );
    }

    /**
     * 清洁任务查询
     *
     * @param cleanData
     * @return
     */
    @Override
    public CleanExeVo result(CleanData cleanData) {
        String workCenter = cleanData.getWokeCenter();
        String cleanName = cleanData.getCleanName();
        String site = CommonMethods.getSite();
        String taskId = cleanData.getHandle();
        CleanExeVo result = new CleanExeVo();
        //审核详情查询
        if (taskId != null && !"".equals(taskId) ) {
            CleanExeItem cei = new CleanExeItem();
            cei.setzCleanExeBo(taskId);
            //查询任务信息
            List<CleanExeItem> cleanExeItems = cleanExeItemService.selectList(cei);
            if (cleanExeItems == null || cleanExeItems.size() < 1) {
                throw BusinessException.build("清洁执行参数不存在");
            }
            result.setCleanExeItemList(cleanExeItems);
            return result;
        }
            //查询清洁信息
            CleanData cleanDataInfo = cleanDataService.getCleanData(site, workCenter, cleanName);
            if (cleanDataInfo == null) {
                throw BusinessException.build("区域：" + workCenter + "的清洁名称" + cleanName + "未维护");
            }
            String zCleanDataBo = cleanDataInfo.getHandle();
            //查询任务信息
            List<CleanExeItem> cleanExeItems = cleanExeItemService.selectCleanExeItemByZCDBo(zCleanDataBo);
            if (cleanExeItems == null || cleanExeItems.size() < 1) {
                //查询清洁信息明细
                List<CleanDataItem> cleanDataItems = cleanDataItemService.getCleanDataItemByZCDBo(zCleanDataBo);
                //CleanDataItem对象转化为CleanExeItem对象
                List<CleanExeItem> cleanExeItemList = new ArrayList<>();
                for (CleanDataItem cdi : cleanDataItems) {
                    JSONObject json = (JSONObject) JSONObject.toJSON(cdi);
                    CleanExeItem cleanExeItem = json.toJavaObject(CleanExeItem.class);
                    cleanExeItemList.add(cleanExeItem);
                }
                result.setCleanExeItemList(cleanExeItemList);
                return result;
            }
            //查询任务编号和任务状态
            String zCleanExeBo ="";
            for (CleanExeItem cei : cleanExeItems) {
                zCleanExeBo = cei.getzCleanExeBo();
                if (zCleanExeBo !=null && !"".equals(zCleanExeBo)){
                    break;
                }
            }
            CleanExe cleanExe = cleanExeService.selectById(zCleanExeBo);
            result.settaskId(cleanExe.getHandle());
            result.setTaskStatus(cleanExe.getTaskStatus());
            result.setCleanExeItemList(cleanExeItems);
            return result;
    }

    /**
     * 任务开始
     *
     * @param cleanData
     * @return
     */
    @Override
    public CleanExeVo startResult(CleanData cleanData) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();

        String workCenter = cleanData.getWokeCenter();
        String cleanName = cleanData.getCleanName();
        CleanExeVo result = new CleanExeVo();
        //查询清洁信息
        CleanData cleanDataInfo = cleanDataService.getCleanData(site, workCenter, cleanName);
        if (cleanDataInfo == null) {
            throw BusinessException.build("区域：" + workCenter + "的清洁名称" + cleanName + "未维护");
        }
        String zCleanDataBo = cleanDataInfo.getHandle();
        //查询任务信息
        List<CleanExeItem> cleanExeItems = cleanExeItemService.selectCleanExeItemByZCDBo(zCleanDataBo);
        if (cleanExeItems == null || cleanExeItems.size() > 1) {
            throw BusinessException.build("任务已经开始或正在进行中");
        }
        //插入到主表
        CleanExe cleanExe = new CleanExe();
        cleanExe.setHandle(IDUtils.createID());
        cleanExe.setzCleanDataBo(zCleanDataBo);
        cleanExe.setTaskStatus( Constants.CLEAN_START );
        cleanExe.setCleaner( user );
        cleanExe.setCreator( user );
        cleanExe.setUpdater( user );
        cleanExe.setCreatedDateTime(new Date());
        cleanExe.setModifiedDateTime(new Date());
        cleanExeService.insert(cleanExe);
        //插入到从表
        String zCleanExeBo =cleanExe.getHandle();
        CleanDataItem cleanDataItem = new CleanDataItem();
        cleanDataItem.setzCleanDataBo(zCleanDataBo);
        List<CleanDataItem> cleanDataItemList = cleanDataItemService.selectList(cleanDataItem);
        for (CleanDataItem cdi :cleanDataItemList) {
            JSONObject job = (JSONObject) JSONObject.toJSON(cdi);
            CleanExeItem cei = job.toJavaObject(CleanExeItem.class);
            cei.setHandle(IDUtils.createID());
            cei.setzCleanExeBo(zCleanExeBo);
            cei.setCreator( user );
            cei.setUpdater( user );
            cei.setCreatedDateTime(new Date());
            cei.setModifiedDateTime(new Date());
            cleanExeItemService.insert(cei);
        }
        //查询出插入的信息
        //List<CleanExeVo> cleanExeVoList = cleanExeService.selectCleanTaskList(zCleanExeBo);
        List<CleanExeItem> list = cleanExeItemService.selectCleanExeItemByZCDBo(zCleanDataBo);
        CleanExe ce = cleanExeService.selectById(cleanExe.getHandle());
        result.settaskId(ce.getHandle());
        result.setTaskStatus(ce.getTaskStatus());
        result.setCleanExeItemList(list);
        return result;
    }

    /**
     * 任务完成
     *
     * @param cleanExeDto
     * @return
     */
    @Override
    public CleanExeVo endResult( CleanExeDto cleanExeDto ) {
        String workCenter = cleanExeDto.getWokeCenter();
        String cleanName = cleanExeDto.getCleanName();
        String taskId = cleanExeDto.gettaskId();
        String user = CommonMethods.getUser();
        CleanExeVo cleanExeVo = new CleanExeVo();
        CleanExe cleanExe = cleanExeService.selectById(taskId);
        if ( cleanExe==null ) {
            throw BusinessException.build("任务未开始，无法完成");
        }
        String taskStatus = cleanExe.getTaskStatus();
        //任务完成不可修改
        if (Constants.CLEAN_COMPLETE.equals(taskStatus) || "".equals(taskStatus)) {
            throw BusinessException.build("区域：" + workCenter + "的清洁名称[" + cleanName + "]的任务["+taskStatus+"]已完成或不存在");
        }
        //更新清洁明细
        List<CleanExeItem> cleanExeItemList =  cleanExeDto.getCleanExeItemList();
        for (CleanExeItem cei : cleanExeItemList) {
            cei.setUpdater(user);
            cei.setModifiedDateTime(new Date());
            cleanExeItemService.updateAllColumnById(cei);
        }
        //任务状态改为完成
        cleanExe.setTaskStatus( Constants.CLEAN_COMPLETE );
        cleanExe.setModifiedDateTime(new Date());
        cleanExeService.updateById(cleanExe);
        //回传跟新后数据
        CleanExeItem cleanExeItem = new CleanExeItem();
        cleanExeItem.setzCleanExeBo(taskId);
        List<CleanExeItem> cleanExeItems = cleanExeItemService.selectList(cleanExeItem);
        cleanExeVo.settaskId(taskId);
        cleanExeVo.setTaskStatus(cleanExe.getTaskStatus());
        cleanExeVo.setCleanExeItemList(cleanExeItems);
        return cleanExeVo;
    }

    /**
     * 任务取消
     *
     * @param cleanExeDto
     * @return
     */
    @Override
    public CleanExeVo cancelResult(CleanExeDto cleanExeDto) {
        String workCenter = cleanExeDto.getWokeCenter();
        String cleanName = cleanExeDto.getCleanName();
        String taskId = cleanExeDto.gettaskId();
        String user = CommonMethods.getUser();
        CleanExeVo cleanExeVo = new CleanExeVo();
        CleanExe cleanExe = cleanExeService.selectById(taskId);
        if ( cleanExe==null ) {
            throw BusinessException.build("任务未开始，无法取消");
        }
        String taskStatus = cleanExe.getTaskStatus();
        //任务取消
        if (Constants.CLEAN_CANCEL.equals(taskStatus) || "".equals(taskStatus)) {
            throw BusinessException.build("区域：" + workCenter + "的清洁名称[" + cleanName + "]的任务["+taskStatus+"]已取消或不存在");
        }
        //改变任务状态
            cleanExe.setTaskStatus(Constants.CLEAN_CANCEL);
            cleanExeService.updateById(cleanExe);
        //回传跟新后数据
        CleanExeItem cleanExeItem = new CleanExeItem();
        cleanExeItem.setzCleanExeBo(taskId);
        List<CleanExeItem> cleanExeItems = cleanExeItemService.selectList(cleanExeItem);
        cleanExeVo.settaskId(taskId);
        cleanExeVo.setTaskStatus(cleanExe.getTaskStatus());
        cleanExeVo.setCleanExeItemList(cleanExeItems);
        return cleanExeVo;
    }

    /**
     * 修改
     * @param cleanExeDto
     * @return
     */
    @Override
    public CleanExeVo updateResult(CleanExeDto cleanExeDto) {
        String workCenter = cleanExeDto.getWokeCenter();
        String cleanName = cleanExeDto.getCleanName();
        String taskId = cleanExeDto.gettaskId();
        String user = CommonMethods.getUser();
        CleanExeVo cleanExeVo = new CleanExeVo();
        CleanExe cleanExe = cleanExeService.selectById(taskId);
        String taskStatus = cleanExe.getTaskStatus();
        //任务完成不可修改
        if (Constants.CLEAN_COMPLETE.equals(taskStatus) || "".equals(taskStatus)) {
            throw BusinessException.build("区域：" + workCenter + "的清洁名称[" + cleanName + "]的任务["+taskStatus+"]已完成或不存在");
        }
        //更新清洁明细
        List<CleanExeItem> cleanExeItemList =  cleanExeDto.getCleanExeItemList();
        for (CleanExeItem cei : cleanExeItemList) {
            cei.setUpdater(user);
            cei.setModifiedDateTime(new Date());
            cleanExeItemService.updateAllColumnById(cei);
        }
        //改变任务状态
        if (taskStatus.equals( Constants.CLEAN_START )) {
            cleanExe.setTaskStatus(Constants.CLEAN_RUN);
            cleanExeService.updateById(cleanExe);
        }
        //回传跟新后数据
        CleanExeItem cleanExeItem = new CleanExeItem();
        cleanExeItem.setzCleanExeBo(taskId);
        List<CleanExeItem> cleanExeItems = cleanExeItemService.selectList(cleanExeItem);
        cleanExeVo.settaskId(taskId);
        cleanExeVo.setTaskStatus(cleanExe.getTaskStatus());
        cleanExeVo.setCleanExeItemList(cleanExeItems);
        return cleanExeVo;
    }

    /**
     * 检索待审核任务
     *
     * @param cleanExeReviewDto
     * @return
     */
    @Override
    public CleanExeReviewVo pendingResult(CleanExeReviewDto cleanExeReviewDto) {
        String workCenter = cleanExeReviewDto.getWokeCenter();
        String cleanName = cleanExeReviewDto.getCleanName();
        Date startTime = cleanExeReviewDto.getStartTime();
        Date endTime = cleanExeReviewDto.getEndTime();
        return null;
    }

    /**
     * 查询待审核任务
     *
     * @param cleanExeReviewDto
     */
    @Override
    public List<CleanExeReviewVo> selectReviewExe(CleanExeReviewDto cleanExeReviewDto) {
        return  cleanExeMapper.selectReviewExe(cleanExeReviewDto);
    }

    /**
     * 保存待审核任务
     *
     * @param cleanExeReviewDto
     */
    @Override
    public CleanExeReviewDto saveReviewExe(CleanExeReviewDto cleanExeReviewDto) {
        String workCenter = cleanExeReviewDto.getWokeCenter();
        String cleanName = cleanExeReviewDto.getCleanName();
        Date startTime = cleanExeReviewDto.getStartTime();
        Date endTime = cleanExeReviewDto.getEndTime();
        String user = CommonMethods.getUser();
        CleanExeReviewDto cleanExeReviewVo = new CleanExeReviewDto();

        List<CleanExeReviewVo> cleanExeReviewVoList = cleanExeReviewDto.getCleanExeReviewVoList();

        //更新任务审核状态
        for (CleanExeReviewVo cleanExeVo : cleanExeReviewVoList) {
            String handle = cleanExeVo.getTaskId();
            String reviewStatus = cleanExeVo.getReviewStatus();
            if (reviewStatus != null && !"".equals(reviewStatus) ) {
                CleanExe cleanExe = new CleanExe();
                cleanExe.setHandle(handle);
                cleanExe.setReviewStatus(reviewStatus);
                cleanExe.setReviewMan( user );
                cleanExeService.updateById(cleanExe);
            }
        }

        //跟新新数据
        cleanExeReviewDto.setCleanExeReviewVoList(null);
        return cleanExeReviewDto;
    }

}